from typing import List
from .model import ResourceConfig
from ninja import Field, ModelSchema, Query, Router
from ninja.pagination import paginate
from utils.fu_crud import (
    ImportSchema,
    create,
    delete,
    export_data,
    import_data,
    retrieve,
    update,
)
from utils.fu_ninja import FuFilters, MyPagination

router = Router()


# 设置过滤字段
class Filters(FuFilters):
        
    des: str = Field(None, alias='des')    
    code: int = Field(None, alias='code')    
    name: str = Field(None, alias='name')


# 设置请求接收字段
class ResourceConfigSchemaIn(ModelSchema):

    class Config:
        model = ResourceConfig
        model_exclude = ['create_time', 'update_time', 'id']


# 设置响应字段
class ResourceConfigSchemaOut(ModelSchema):

    class Config:
        model = ResourceConfig
        model_fields = '__all__'


# 创建ResourceConfig
@router.post('/resource_config', response=ResourceConfigSchemaOut)
def create_resource_config(request, data: ResourceConfigSchemaIn):
    test_demo = create(request, data, ResourceConfig)
    return test_demo


# 删除ResourceConfig
@router.delete('/resource_config/{id}')
def delete_resource_config(request, id: str):
    delete(id, ResourceConfig)
    return {'success': True}


# 更新ResourceConfig
@router.put('/resource_config/{id}', response=ResourceConfigSchemaOut)
def update_resource_config(request, id: str, data: ResourceConfigSchemaIn):
    test_demo = update(request, id, data, ResourceConfig)
    return test_demo


# 获取ResourceConfig
@router.get('/resource_config', response=List[ResourceConfigSchemaOut])
@paginate(MyPagination)
def list_resource_config(request, filters: Filters = Query(...)):
    qs = retrieve(request, ResourceConfig, filters)
    return qs


# 导入
@router.get('/resource_config/all/export')
def export_resource_config(request):
    export_fields = ('des', 'code', 'name', )
    return export_data(request, ResourceConfig, ResourceConfigSchemaOut, export_fields)


# 导出
@router.post('/resource_config/all/import')
def import_resource_config(request, data: ImportSchema):
    import_fields = ('des', 'code', 'name', )
    return import_data(request, ResourceConfig, ResourceConfigSchemaIn, data, import_fields)
    